import { useState, useRef } from 'react'

function Sun(props) {
  // props包含父组件传递过来的所有数据
  console.log(props)
  const { onGetSun } = props
  const sonvalue = '展示子组件传递的数据'
  // 父传子
  // 子组件中不允许直接修改父组件的值（谁的数据谁修改）

  return (
    <div>
      {props?.name}
      jsx:{props?.child}
      {props?.children}
      <button
        onClick={() => {
          onGetSun(sonvalue)
        }}
      >
        给父组件传值
      </button>
    </div>
  )
}

function A(props) {
  const { onTransA } = props
  return (
    <div>
      我是A组件{' '}
      <button
        onClick={() => {
          onTransA('我是A传递给B组件的数据')
        }}
      >
        点击给B组件传递数据
      </button>
    </div>
  )
}
function B(props) {
  const { value } = props
  return <div>我是B组件 {value}</div>
}

// useref生成ref对象，绑定到dom标签上
// dom可用时，ref.current获取dom

function App() {
  const name = 'this is a sun'
  const [value, setValue] = useState('')
  const inputref = useRef(null)
  const showDom = () => {
    console.dir(inputref.current)
  }
  const [message, setMsg] = useState('')
  const getMessage = (msg) => {
    console.log('接收到子组件传递的参数', msg)
    setMsg(msg)
  }

  const [Avalue, setAValue] = useState('')
  const getAvalue = (msg) => {
    console.log('接收到A组件传递的数据', msg)
    setAValue(msg)
  }
  return (
    <>
      <div>
        {/* 父组件可以给子组件传递任意的数据 */}
        {/* 字符串，数值，数组，对象，函数，jsx都可 */}
        <Sun
          name={name}
          age={18}
          isTrue={false}
          list={['1', '2']}
          obj={{ name: 'sys' }}
          cb={() => {
            console.log('123')
            return '123'
          }}
          child={<div>这是子组件</div>}
        />
        <Sun onGetSun={getMessage}>
          <span>this is a span</span>
        </Sun>
        {message}
        <button onClick={() => setValue(value + 1)}>{value}</button>
        <input type="text" value={value} onChange={(e) => setValue(e.target.value)} />
        <input type="text" ref={inputref} />
        <button onClick={showDom}>获取dom</button>
        <A onTransA={getAvalue}></A>
        <B value={Avalue}></B>
      </div>
    </>
  )
}

export default App
